package com.monitor.service.monitor;

import com.monitor.model.MonitorConfig;
import com.monitor.model.ServerConfig;
import com.monitor.model.ServerStatus;
import com.monitor.service.parser.MetricParser;
import com.monitor.service.parser.MetricParserFactory;
import com.monitor.util.SSHClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Linux服务器监控实现类
 * 实现针对Linux服务器的具体监控逻辑
 */
public class LinuxServerMonitorImpl extends AbstractServerMonitor {
    private static final Logger logger = LoggerFactory.getLogger(LinuxServerMonitorImpl.class);

    /**
     * 构造函数
     * @param serverConfig 服务器配置
     * @param monitorConfig 监控配置
     */
    public LinuxServerMonitorImpl(ServerConfig serverConfig, MonitorConfig monitorConfig) {
        super(serverConfig, monitorConfig);
    }

    /**
     * 收集服务器指标，根据配置的监控项执行相应命令
     */
    @Override
    protected void collectServerMetrics(SSHClient sshClient, ServerStatus status) {
        for (String item : serverConfig.getMonitorItems()) {
            try {
                executeMonitorItem(sshClient, status, item);
            } catch (Exception e) {
                logger.error("执行监控项 {} 失败: {}", item, e.getMessage());
            }
        }
    }

    /**
     * 执行单个监控项
     * @param sshClient SSH客户端
     * @param status 服务器状态对象，用于保存结果
     * @param item 监控项名称（如cpu, memory等）
     */
    private void executeMonitorItem(SSHClient sshClient, ServerStatus status, String item) {
        // 检查监控项是否在配置中
        if (!monitorConfig.getCommands().containsKey(item)) {
            logger.warn("未找到监控项 {} 的命令配置", item);
            return;
        }
        
        String command = monitorConfig.getCommands().get(item);
        
        // 服务状态监控需要特殊处理
        if ("services".equals(item)) {
            checkServicesStatus(sshClient, status);
            return;
        }
        
        // 执行命令并获取结果
        String result = sshClient.executeCommand(command);
        
        // 使用解析器工厂获取相应的解析器并解析结果
        MetricParser parser = MetricParserFactory.getParser(item);
        if (parser != null) {
            parser.parse(result, status);
        } else {
            // 如果没有对应的解析器，直接设置结果
            logger.warn("未找到监控项 {} 的解析器", item);
            if ("network".equals(item)) {
                status.setNetworkConnections(result.trim());
            }
        }
    }

    /**
     * 检查服务状态
     * @param sshClient SSH客户端
     * @param status 服务器状态
     */
    private void checkServicesStatus(SSHClient sshClient, ServerStatus status) {
        // 获取需要监控的服务列表
        List<String> services = monitorConfig.getServiceList();
        if (services == null || services.isEmpty()) {
            logger.info("服务列表为空，跳过服务状态检查");
            return;
        }
        
        List<ServerStatus.ServiceStatus> serviceStatusList = new ArrayList<>();
        
        // 通过systemctl检查每个服务的状态
        for (String service : services) {
            String command = String.format("systemctl status %s | head -n 3", service);
            String result = sshClient.executeCommand(command);
            
            ServerStatus.ServiceStatus serviceStatus = new ServerStatus.ServiceStatus();
            serviceStatus.setName(service);
            
            // 解析服务状态
            if (result.contains("Active: active (running)")) {
                serviceStatus.setStatus("运行中");
                serviceStatus.setRunning(true);
            } else if (result.contains("Active: inactive")) {
                serviceStatus.setStatus("已停止");
                serviceStatus.setRunning(false);
            } else if (result.contains("Active: failed")) {
                serviceStatus.setStatus("失败");
                serviceStatus.setRunning(false);
            } else {
                serviceStatus.setStatus("未知");
                serviceStatus.setRunning(false);
            }
            
            serviceStatusList.add(serviceStatus);
        }
        
        status.setServices(serviceStatusList);
    }
} 